import React, { useState, useEffect } from "react";

const vendors = [
  {
    name: "OpenAI",
    api: "/api/openai-tts",
    models: ["tts-1", "tts-1-hd", "gpt-4o-mini-tts"],
    voices: ["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "shimmer", "sage", "nova"],
    formats: ["mp3", "opus", "aac", "flac", "wav", "pcm"],
    hasScenes: false
  },
  {
    name: "智谱清言",
    api: "/api/zhipu-tts",
    models: ["default"], // 根据实际API填写
    voices: ["default"], // 根据实际API填写
    formats: ["mp3"],
    hasScenes: false
  },
  {
    name: "火山引擎",
    api: "/api/volcano-tts",
    models: ["default"],
    formats: ["mp3", "wav", "pcm", "ogg_opus"],
    hasScenes: true,
    scenes: [
      "通用场景",
      "趣味方言",
      "角色扮演",
      "多语种",
      "播报解说",
      "传统音色"
    ],
    voicesByScene: {
      "通用场景": [
        "zh_female_shuangkuaisisi_moon_bigtts|爽快思思/Skye(通用场景)",
        "zh_male_wennuanahu_moon_bigtts|温暖阿虎/Alvin(通用场景)",
        "zh_male_shaonianzixin_moon_bigtts|少年梓辛/Brayan(通用场景)",
        "zh_female_linjianvhai_moon_bigtts|邻家女孩(通用场景)",
        "zh_male_yuanboxiaoshu_moon_bigtts|渊博小叔(通用场景)",
        "zh_male_yangguangqingnian_moon_bigtts|阳光青年(通用场景)",
        "zh_female_tianmeixiaoyuan_moon_bigtts|甜美小源(通用场景)",
        "zh_female_qingchezizi_moon_bigtts|清澈梓梓(通用场景)",
        "zh_male_jieshuoxiaoming_moon_bigtts|解说小明(通用场景)",
        "zh_female_kailangjiejie_moon_bigtts|开朗姐姐(通用场景)",
        "zh_male_linjiananhai_moon_bigtts|邻家男孩(通用场景)",
        "zh_female_tianmeiyueyue_moon_bigtts|甜美悦悦(通用场景)",
        "zh_female_xinlingjitang_moon_bigtts|心灵鸡汤(通用场景)",
        "zh_female_cancan_mars_bigtts|灿灿(通用场景)",
        "zh_female_zhixingnvsheng_mars_bigtts|知性女声(通用场景)",
        "zh_female_qingxinnvsheng_mars_bigtts|清新女声(中/英通用)"
      ],
      "趣味方言": [
        "zh_female_wanqudashu_moon_bigtts|湾区大叔(方言)",
        "zh_female_daimengchuanmei_moon_bigtts|呆萌川妹(方言)",
        "zh_male_guozhoudege_moon_bigtts|广州德哥(方言)",
        "zh_male_beijingxiaoye_moon_bigtts|北京小爷(方言)",
        "zh_male_haoyuxiaoge_moon_bigtts|浩宇小哥(方言)",
        "zh_male_guangxiyuanzhou_moon_bigtts|广西远舟(方言)",
        "zh_female_meituojieer_moon_bigtts|妹坨洁儿(方言)",
        "zh_male_yuzhouzixuan_moon_bigtts|豫州子轩(方言)",
        "zh_male_jingqiangkanye_moon_bigtts|京腔侃爷/Harmony(方言)",
        "zh_female_wanwanxiaohe_moon_bigtts|湾湾小何(方言)"
      ],
      "角色扮演": [
        "zh_female_meilinvyou_moon_bigtts|魅力女友(角色扮演)",
        "zh_male_shenyeboke_moon_bigtts|深夜播客(角色扮演)",
        "zh_female_sajiaonvyou_moon_bigtts|柔美女友(角色扮演)",
        "zh_female_yuanqinvyou_moon_bigtts|撒娇学妹(角色扮演)",
        "zh_female_gaolengyujie_moon_bigtts|高冷御姐(角色扮演)",
        "zh_male_aojiaobazong_moon_bigtts|傲娇霸总(角色扮演)",
        "zh_female_wenrouxiaoya_moon_bigtts|温柔小雅(角色扮演)",
        "zh_male_dongfanghaoran_moon_bigtts|东方浩然(角色扮演)",
        "ICL_zh_female_bingruoshaonv_tob|病弱少女(角色扮演)",
        "ICL_zh_female_huoponvhai_tob|活泼女孩(角色扮演)",
        "ICL_zh_female_heainainai_tob|和蔼奶奶(角色扮演)",
        "ICL_zh_female_linjuayi_tob|邻居阿姨(角色扮演)",
        "zh_male_tiancaitongsheng_mars_bigtts|天才童声(角色扮演)",
        "zh_male_naiqimengwa_mars_bigtts|奶气萌娃(角色扮演)",
        "zh_male_sunwukong_mars_bigtts|猴哥(角色扮演)",
        "zh_male_xionger_mars_bigtts|熊二(角色扮演)",
        "zh_female_peiqi_mars_bigtts|佩奇猪(角色扮演)",
        "zh_female_popo_mars_bigtts|婆婆(角色扮演)"
      ],
      "多语种": [
        "multi_female_shuangkuaisisi_moon_bigtts|はるこ/Esmeralda(日/西)",
        "multi_male_jingqiangkanye_moon_bigtts|かずね/Javier(日/西)",
        "multi_female_gaolengyujie_moon_bigtts|あけみ(日语)",
        "multi_male_wanqudashu_moon_bigtts|ひろし/Roberto(日/西)",
        "en_female_anna_mars_bigtts|Anna(英文)"
      ],
      "播报解说": [
        "zh_male_changtianyi_mars_bigtts|悬疑解说(播报)"
      ],
      "传统音色": [
        "zh_female_qingxin|传统-女声清新",
        "zh_male_qingxin|传统-男声清新",
        "zh_female_wenzhong|传统-女声稳重",
        "zh_male_wenzhong|传统-男声稳重"
      ]
    },
    // 向下兼容的音色列表
    voices: []
  }
];

// 初始化火山引擎的voices字段，以保持向下兼容性
const initVoicesList = () => {
  const volcanoVendor = vendors.find(v => v.name === "火山引擎");
  if (volcanoVendor && volcanoVendor.hasScenes) {
    volcanoVendor.voices = Object.values(volcanoVendor.voicesByScene).flat();
  }
};
initVoicesList();

// 示例文本
const exampleTexts = [
  "人工智能正在改变我们的世界，让生活更加便捷。",
  "春天来了，花儿绽放，小鸟在枝头歌唱。",
  "科技的进步让人类的生活变得更加丰富多彩。",
  "海浪拍打着沙滩，留下一道道优美的痕迹。"
];

function App() {
  const [vendorIdx, setVendorIdx] = useState(0);
  const [text, setText] = useState("");
  const [model, setModel] = useState(vendors[0].models[0]);
  const [scene, setScene] = useState(""); // 新增场景状态
  const [voice, setVoice] = useState(vendors[0].voices[0]);
  const [format, setFormat] = useState(vendors[0].formats[0]);
  const [audioUrl, setAudioUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [speed, setSpeed] = useState(1.0);
  const [hasGenerated, setHasGenerated] = useState(false);
  // 主题状态，默认跟随系统
  const [theme, setTheme] = useState(() => {
    // 首先检查本地存储中的主题设置
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      return savedTheme;
    }
    // 如果没有本地存储，检查系统偏好
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  });

  // 获取当前选中厂商的场景列表
  const getScenes = () => {
    const vendor = vendors[vendorIdx];
    return vendor.hasScenes ? vendor.scenes : [];
  };

  // 获取当前场景的语音列表
  const getVoicesByScene = () => {
    const vendor = vendors[vendorIdx];
    if (!vendor.hasScenes || !scene) {
      return vendor.voices;
    }
    return vendor.voicesByScene[scene] || [];
  };

  // 添加提示框组件
  const AlertBox = ({ message, type = "warning" }) => {
    const backgroundColor = {
      info: getThemeStyles('#e8f0fe', '#192e4d'),
      warning: getThemeStyles('#fff8e6', '#332b00'),
      error: getThemeStyles('#fdeded', '#330000')
    }[type];
    
    const borderColor = {
      info: getThemeStyles('#c2d7ff', '#3a5d9f'),
      warning: getThemeStyles('#ffe4a6', '#665500'),
      error: getThemeStyles('#f6cece', '#661a1a')
    }[type];
    
    const textColor = {
      info: getThemeStyles('#1a73e8', '#5a9cff'),
      warning: getThemeStyles('#b78103', '#ffd966'),
      error: getThemeStyles('#ea4335', '#ff8a80')
    }[type];

    return (
      <div
        style={{
          padding: "12px 16px",
          backgroundColor,
          borderLeft: `4px solid ${borderColor}`,
          borderRadius: "4px",
          color: getThemeStyles('#333', '#f0f0f0'),
          margin: "12px 0",
          fontSize: "0.95rem",
          display: "flex",
          alignItems: "center"
        }}
      >
        {type === "info" && (
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={textColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: "12px" }}>
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="12" y1="16" x2="12" y2="12"></line>
            <line x1="12" y1="8" x2="12.01" y2="8"></line>
          </svg>
        )}
        {type === "warning" && (
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={textColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: "12px" }}>
            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>
            <line x1="12" y1="9" x2="12" y2="13"></line>
            <line x1="12" y1="17" x2="12.01" y2="17"></line>
          </svg>
        )}
        {type === "error" && (
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={textColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: "12px" }}>
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="15" y1="9" x2="9" y2="15"></line>
            <line x1="9" y1="9" x2="15" y2="15"></line>
          </svg>
        )}
        <span>{message}</span>
      </div>
    );
  };

  // 获取音色ID和显示名称的辅助函数
  const getVoiceId = (voiceOption) => {
    return voiceOption.includes('|') ? voiceOption.split('|')[0] : voiceOption;
  };
  
  const getVoiceDisplayName = (voiceOption) => {
    return voiceOption.includes('|') ? voiceOption.split('|')[1] : voiceOption;
  };

  // 主题切换函数
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
    localStorage.setItem('theme', newTheme); // 保存到本地存储
    document.documentElement.setAttribute('data-theme', newTheme);
  };

  // 初始化时应用主题
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // 获取主题相关的样式
  const getThemeStyles = (lightStyle, darkStyle) => {
    return theme === 'dark' ? darkStyle : lightStyle;
  };

  // 处理厂商切换
  useEffect(() => {
    const vendor = vendors[vendorIdx];
    if (vendor.hasScenes) {
      // 如果有场景选择，设置默认场景
      const defaultScene = vendor.scenes[0];
      setScene(defaultScene);
      // 设置该场景的第一个语音
      const scenesVoices = vendor.voicesByScene[defaultScene] || [];
      if (scenesVoices.length > 0) {
        setVoice(scenesVoices[0]);
      }
    } else {
      // 无场景，清空场景选择
      setScene("");
      setVoice(vendor.voices[0]);
    }
  }, [vendorIdx]);

  // 处理场景切换
  useEffect(() => {
    if (scene) {
      const vendor = vendors[vendorIdx];
      if (vendor.hasScenes) {
        const scenesVoices = vendor.voicesByScene[scene] || [];
        if (scenesVoices.length > 0) {
          setVoice(scenesVoices[0]);
        }
      }
    }
  }, [scene, vendorIdx]);

  useEffect(() => {
    // 清除旧的音频URL
    return () => {
      if (audioUrl) {
        URL.revokeObjectURL(audioUrl);
      }
    };
  }, [audioUrl]);

  const handleVendorChange = (idx) => {
    setVendorIdx(idx);
    setModel(vendors[idx].models[0]);
    setFormat(vendors[idx].formats[0]);
    // 场景和语音会在useEffect中处理
  };

  const insertExampleText = () => {
    const randomText = exampleTexts[Math.floor(Math.random() * exampleTexts.length)];
    setText(randomText);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!text.trim()) {
      alert("请输入要生成的文本");
      return;
    }
    
    setLoading(true);
    setAudioUrl(null);
    
    try {
      const vendor = vendors[vendorIdx];
      
      // 使用相对路径确保走代理
      const apiUrl = vendor.api;
      console.log(`正在调用API: ${apiUrl}`);
      
      const res = await fetch(apiUrl, {
        method: "POST",
        headers: { 
          "Content-Type": "application/json",
          "X-Requested-With": "XMLHttpRequest" 
        },
        body: JSON.stringify({
          input: text,
          model,
          voice: getVoiceId(voice), // 确保只发送音色ID，不包含显示名称
          response_format: format,
          speed: parseFloat(speed)
        }),
        credentials: "same-origin"
      });
      
      if (!res.ok) {
        const errorText = await res.text();
        throw new Error(`服务器返回错误 (${res.status}): ${errorText}`);
      }
      
      const blob = await res.blob();
      setAudioUrl(URL.createObjectURL(blob));
      setHasGenerated(true);
    } catch (error) {
      console.error("生成失败:", error);
      alert(`生成失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 当前可选场景
  const scenes = getScenes();
  // 当前场景下的语音列表
  const currentVoices = getVoicesByScene();

  return (
    <div className="app-container" style={{ maxWidth: 800, margin: "20px auto" }}>
      <header style={{ 
        textAlign: "center", 
        marginBottom: "32px",
        position: "relative" // 为主题按钮定位添加相对定位
      }}>
        {/* 主题切换按钮 */}
        <button
          onClick={toggleTheme}
          style={{
            position: "absolute",
            right: 0,
            top: 0,
            background: "transparent",
            border: "none",
            padding: "8px",
            cursor: "pointer",
            boxShadow: "none",
            color: getThemeStyles('#333', '#f0f0f0')
          }}
          title={theme === 'light' ? "切换到深色模式" : "切换到浅色模式"}
        >
          {theme === 'light' ? (
            // 月亮图标 (深色模式)
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
            </svg>
          ) : (
            // 太阳图标 (浅色模式)
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="5"></circle>
              <line x1="12" y1="1" x2="12" y2="3"></line>
              <line x1="12" y1="21" x2="12" y2="23"></line>
              <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
              <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
              <line x1="1" y1="12" x2="3" y2="12"></line>
              <line x1="21" y1="12" x2="23" y2="12"></line>
              <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
              <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
            </svg>
          )}
        </button>
        
        <h1 style={{ fontSize: "2.2rem", marginBottom: "8px", background: "linear-gradient(135deg, #1a73e8 0%, #6c5ce7 100%)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>
          AI语音生成合集
        </h1>
        <p style={{ color: getThemeStyles('#666', '#b0b0b0'), fontSize: "1.1rem" }}>支持多种AI模型的高质量语音合成</p>
      </header>

      <div className="card" style={{ backgroundColor: getThemeStyles('#ffffff', '#1e1e1e'), boxShadow: getThemeStyles('0 4px 12px rgba(0, 0, 0, 0.08)', '0 4px 12px rgba(0, 0, 0, 0.3)') }}>
        {/* 厂商选择标签 */}
        <div className="vendor-tabs">
          {vendors.map((v, i) => (
            <div 
              key={v.name} 
              className={`vendor-tab ${i === vendorIdx ? 'active' : ''}`}
              onClick={() => handleVendorChange(i)}
            >
              {v.name}
            </div>
          ))}
        </div>

        {/* 智谱清言状态提示 */}
        {vendorIdx === 1 && (
          <AlertBox 
            message="当前智谱模型并未正常对接，有能力可自行适配" 
            type="warning" 
          />
        )}

        <form onSubmit={handleSubmit}>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
            <div>
              <label>模型选择</label>
              <select value={model} onChange={e => setModel(e.target.value)}>
                {vendors[vendorIdx].models.map(m => 
                  <option value={m} key={m}>{m}</option>
                )}
              </select>
            </div>
            {vendors[vendorIdx].hasScenes && scenes.length > 0 ? (
              <div>
                <label>使用场景</label>
                <select value={scene} onChange={e => setScene(e.target.value)}>
                  {scenes.map(s => 
                    <option value={s} key={s}>{s}</option>
                  )}
                </select>
              </div>
            ) : null}
          </div>

          <div style={{ marginTop: vendors[vendorIdx].hasScenes ? "20px" : "0", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "20px" }}>
            <div>
              <label>语音角色</label>
              <select value={voice} onChange={e => setVoice(e.target.value)}>
                {currentVoices.map(v => 
                  <option value={v} key={v}>
                    {getVoiceDisplayName(v)}
                  </option>
                )}
              </select>
            </div>
            <div>
              <label>音频格式</label>
              <select value={format} onChange={e => setFormat(e.target.value)}>
                {vendors[vendorIdx].formats.map(f => 
                  <option value={f} key={f}>{f.toUpperCase()}</option>
                )}
              </select>
            </div>
          </div>

          <div style={{ marginTop: "20px" }}>
            <label>语速调节 ({speed}x)</label>
            <input 
              type="range" 
              min="0.5" 
              max="2.0" 
              step="0.1" 
              value={speed} 
              onChange={e => setSpeed(e.target.value)}
              style={{ width: "100%", height: "38px" }} 
            />
          </div>

          <div style={{ marginTop: "20px" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <label>文本内容</label>
              <button 
                type="button" 
                onClick={insertExampleText}
                style={{ 
                  padding: "4px 8px", 
                  fontSize: "0.8rem",
                  background: "transparent",
                  color: "#1a73e8",
                  boxShadow: "none",
                  border: "1px solid #1a73e8"
                }}
              >
                插入示例文本
              </button>
            </div>
            <textarea 
              value={text} 
              onChange={e => setText(e.target.value)} 
              rows={5} 
              placeholder="请输入要转换为语音的文本..."
            />
          </div>

          <div style={{ display: "flex", justifyContent: "center", marginTop: "24px" }}>
            <button 
              type="submit" 
              disabled={loading || !text.trim()} 
              className={loading ? 'loading' : ''}
              style={{ width: "200px", height: "48px" }}
            >
              {loading ? "生成中..." : "生成语音"}
            </button>
          </div>
        </form>

        {hasGenerated && (
          <div 
            style={{ 
              marginTop: "32px", 
              padding: "24px", 
              borderRadius: "8px", 
              backgroundColor: getThemeStyles('#f5f7fa', '#252525'), 
              border: `1px solid ${getThemeStyles('#e0e0e0', '#3a3a3a')}`,
              color: getThemeStyles('inherit', '#e0e0e0')
            }}
          >
            <h3 style={{ margin: "0 0 16px 0" }}>生成结果</h3>
            
            {audioUrl ? (
              <>
                <audio 
                  controls 
                  src={audioUrl} 
                  style={{ 
                    width: "100%", 
                    backgroundColor: getThemeStyles('inherit', '#333'),
                    borderRadius: "8px"
                  }} 
                />
                <div style={{ display: "flex", justifyContent: "center", marginTop: "8px" }}>
                  <a href={audioUrl} download={`speech.${format}`} className="download-btn" style={{ backgroundColor: getThemeStyles('#34a853', '#2d9348') }}>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight: "8px" }}>
                      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                      <polyline points="7 10 12 15 17 10"></polyline>
                      <line x1="12" y1="15" x2="12" y2="3"></line>
                    </svg>
                    下载语音文件
                  </a>
                </div>
              </>
            ) : (
              <div style={{ textAlign: "center", padding: "32px 0", color: getThemeStyles('#666', '#b0b0b0') }}>
                {loading ? (
                  <div className="loading">正在生成语音，请稍候...</div>
                ) : (
                  <div>音频生成失败，请重试</div>
                )}
              </div>
            )}
          </div>
        )}
      </div>

      <footer style={{ textAlign: "center", marginTop: "40px", color: getThemeStyles('#888', '#888'), fontSize: "0.9rem" }}>
        <p>支持多种AI语音合成服务 • 使用 React 和 Python Flask 构建</p>
      </footer>
    </div>
  );
}

export default App;
